/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package NetCommunicator;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author gianmariospacagna
 */
public class NetCommunicator {

    InetAddress serverLocation;
    int serverPort;

    public NetCommunicator(InetAddress serverLocation, int serverPort) {
        this.serverLocation = serverLocation;
        this.serverPort = serverPort;
    }

    public void sendData(Serializable data) throws ServerDownException {
        SocketAddress sa = new InetSocketAddress(serverLocation, serverPort);
        Socket socket = new Socket();
        try {
            socket.connect(sa);
            OutputStream os = socket.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(data);
            oos.flush();
            oos.close();
            socket.close();
        } catch (IOException ex) {

            Logger.getLogger(NetCommunicator.class.getName()).log(Level.SEVERE, null, ex);
            throw new ServerDownException();
        }

    }
}
